<?php

/* Checks a user name and password against the members database
* to start a new login session.
*
* @method post
* @header username The username of the user. This corresponds to the
* 'usr' column in the members table.
* @header password The password of the user.
*
* @return "login successful"
*          If the login was a success
* @return "username or password incorrect"
*          If the credentials were empty or the database returned an error
*/	

include_once("connect_to_database.php");
include_once("session.php");
require_once ("colorsArray.php");

$success = "login successful";
$error = "username or password incorrect";

if(!$_POST['username'] || !$_POST['password']){
	echo($error);

}else{

	//retrieve sql escaped login parameters
	$user = mysql_real_escape_string($_POST['username']);
	$pass = mysql_real_escape_string($_POST['password']);

	$querry = "SELECT id,username FROM members WHERE username='$user' AND password='".md5($pass)."';";

	$result = mysql_query($querry);	
	$row = mysql_fetch_assoc($result);

	if($row['username'] == $user){
		/* If everything is OK login and set the [color] column to a random color value.
		 * This way every user gets a randomly picked color for the chat everytime he logs in.
		 * */
	
		$_SESSION['usr']=$row['username'];
		$_SESSION['id'] = $row['id'];
		$color = colors();
		mysql_query("UPDATE members SET color = '".$color."', isOnline = '1' WHERE username = '".$user."'");
	
		echo($success);
	}else{
		echo($error);
	}
}
	

?>
